package com.suke.czx.modules.sys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.suke.czx.common.utils.CodeConstant;
import com.suke.czx.common.utils.Constant;
import com.suke.czx.common.utils.R;
import com.suke.czx.modules.sys.entity.SysUser;
import com.suke.czx.modules.sys.mapper.SysUserMapper;
import com.suke.czx.modules.sys.service.SysUserRoleService;
import com.suke.czx.modules.sys.service.SysUserService;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * 应用模块名称: 系统用户
 * 代码描述: 系统用户业务层
 * copyright: AUZAR ALL RIGHTS RESERVED
 * company: AUZAR
 *
 * @author: 颜米晨
 * @date: 2021/08/27 16:31
 */
@Lazy
@Service
@AllArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

	private final SysUserMapper sysUserMapper;

	private final SysUserRoleService sysUserRoleService;

	private final PasswordEncoder passwordEncoder;

	/**
	 * 保存用户
	 * @param user 用户
	 * @return VO
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R saveUser(SysUser user) {
		user.setRoleIdList(Arrays.stream(StrUtil.split(user.getRoleIds(), Constant.COMMA)).map(Long::valueOf).collect(Collectors.toList()));
		user.setStatus(CodeConstant.STATUS_NORMAL);
		user.setCreateTime(new Date());
		user.setPassword(passwordEncoder.encode(user.getPassword()));
		baseMapper.insert(user);
		//保存用户与角色关系
		sysUserRoleService.fullUpdateUserRoleList(user.getUserId(), user.getRoleIdList());
		return R.ok();
	}

	/**
	 * 更新用户
	 * @param user 用户
	 * @return VO
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R updateUser(SysUser user) {
		user.setRoleIdList(Arrays.stream(StrUtil.split(user.getRoleIds(), Constant.COMMA)).map(Long::valueOf).collect(Collectors.toList()));
		// 用户名和密码不允许更新
		user.setUsername(null);
		user.setPassword(null);
		baseMapper.updateById(user);
		//保存用户与角色关系
		sysUserRoleService.fullUpdateUserRoleList(user.getUserId(), user.getRoleIdList());
		return R.ok();
	}

	/**
	 * 更新用户密码
	 * @param userId 用户id
	 * @param newPassword 新密码
	 * @return VO
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R updateUserPassword(Long userId, String newPassword) {
		sysUserMapper.updateUserPassword(userId, newPassword);
		return R.ok();
	}

	/**
	 * 更新用户状态
	 * @param userId 用户编码
	 * @param status 用户状态
	 * @param operatorId 操作者编码
	 * @return VO
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R updateUserStatus(Long userId, Integer status, Long operatorId) {
		sysUserMapper.updateUserStatus(userId, status, operatorId);
		return R.ok();
	}

}
